import collections


class Solution(object):
    def removeStones(self, stones):
        self.c = 0
        n = len(stones)
        p = [i for i in range(n)]
        h_d = collections.defaultdict(list)
        v_d = collections.defaultdict(list)
        for i, s in enumerate(stones):
            h_d[s[0]].append(i)
            v_d[s[1]].append(i)

        def find(x):
            if p[x] == x:
                return x
            else:
                p[x] = find(p[x])
                return p[x]

        def union(x, y):
            rootx = find(x)
            rooty = find(y)
            if rootx != rooty:
                if rootx > rooty:
                    p[rootx] = rooty
                else:
                    p[rooty] = rootx
                self.c += 1

        for key in h_d:
            t = h_d[key]
            for i in range(1, len(t)):
                union(t[0], t[i])

        for key in v_d:
            t = v_d[key]
            for i in range(1, len(t)):
                union(t[0], t[i])
        return self.c


data = Solution()
stones = [[0, 0], [0, 1], [1, 0], [1, 2], [2, 1], [2, 2]]
print(data.removeStones(stones))
